<?php
class XML {
	public $doc;
	public $editmode;
	public $adminmode;
	public $cache = 0;
	public $cachefilename;
	public $replaceglobalurls;
	public $presence;

	/**
	* @return void
	* @param integer $editmode
	* @desc reads an xmlfile
	*/
	function __construct($editmode=0, $replaceglobalurls=1) {
		$this->doc = new DOMDocument("1.0", "utf-8");
		
		$root = $this->doc->createElement("document");
		$this->doc->appendChild($root);

		$this->editmode=$editmode;
		$this->replaceglobalurls=$replaceglobalurls;
		$this->add_standards();
		if(!defined("EDITMODE")) {
			define("EDITMODE", $editmode);
		}
	}

	/**
	* @return void
	* @param string $file
	* @desc reads an xmlfile
	*/
	public function read_xml_file($file) {
		$fc=file_get_contents($file);
		$this->doc->loadXML($fc);
	}

	/**
	* @return void
	* @param string $name
	* @param string $content
	* @param string $path
	* @param array $attributes
	* @desc add a tree node
	*/
	public function add_node($name, $content = "", $path = null, $attributes = null, $cdata=0, $supressentities=0) {
		$xp=$this->get_xpath_node($path);
		if ($xp->length>0) {
			if ($cdata==1) {
				$newelem=$this->doc->createElement($name, "");
				$newcdata=$this->doc->createCDATASection($content);
				$newelem->appendChild($newcdata);
			} else {
				if($cdata==0 && $supressentities==0) {
					$content=htmlentities($content);
				}
				$newelem=$this->doc->createElement($name, $content);
			}
			for($i=0; $i<$xp->length; $i++) {
				$this->add_tree_node_param($newelem, $attributes);
				$xp->item($i)->appendChild($newelem);
			}
		}
	}

	/**
	* @return string
	* @param string node
	* @desc reads a node of the treec
	*/
	public function read_node($node) {
		$xp=$this->get_xpath_node($node);
		return $node=$xp->item(0)->nodeValue;
	}

	function add_tree_node_param($node, $attributes)
	{
		//		$xp=$this->get_xpath_node($node);
		if (is_array($attributes))
		{
			while (list ($key, $val) = each ($attributes)) {
				$node->setAttribute($key, $val);
				// $xp->item(0)->setAttribute($key, $val);
			}
			// $act_attributes=$xp->item(0)->
			/*
			$attribs=$tag->attributes();
			for ($j=0; $j<count($attribs); $j++)
			{
			$act_att=$attribs[$j];
			$property[$act_att->name]=$act_att->value;
			}
			while (list ($key, $val) = each ($property))
			{
			$new_attribs=$tag->set_attribute($key, $val);
			} */
		}
		// print_r($node);
		// return $node;
		// $tag->append_child($new_attribs);
	}

	/**
	* @return void
	* @param string node
	* @desc reads a node of the tree
	*/
	public function write_node_content($node, $name, $content, $cdata=0) {
		$xp=$this->get_xpath_node($node ."/". $name);
		// print_r($xp->length);
		if ($xp->length>0) {
			if ($cdata==0) {
				$newelem=$this->doc->createElement($name, $content);
			} else {
				$newelem=$this->doc->createElement($name, $this->doc->createCDATASection($content));
			}
			for($i=0; $i<$xp->length; $i++) {
				$oldNode=$xp->item($i);
				$oldNode->parentNode->replaceChild($newelem, $oldNode);
			}
		}
		// return $node=$xp->item(0)->nodeValue;
	}
	
	public function add_additional_nodes($array) {
		$this->add_node("additional");
		while(list($key, $val) = each($array)) {
			$attribs=null;
			if(isset($val[1]) && is_array($val[1])) {
				$attribs=$val[1];
			}
			$this->add_node($key, $val[0], "/additional", $attribs, 1);
		}
	}

	/**
	* @return object
	* @param string node
	* @desc gets xpath node
	*/
	private function get_xpath_node($node) {
		if (substr($node, 0, 9)!="/document") {
			$node="/document". $node;
		}
		$xpath = new domXPath($this->doc);
		$query = $node;
		$xpathQuery = $xpath->query($query);
		return $xpathQuery;
	}

	public function get_cache($presence, $language, $docuid) {
		$this->presence = $presence;
		$filename=realpath("./../cache/". $presence)."/". $language ."_";
		if(!empty($_SESSION["act_navi"])) {
			$filename.=$_SESSION["act_navi"];
		}
		if(!empty($_SESSION["act_doc"])) {
			$filename.="_". $_SESSION["act_doc"];
		}
		$getparams="";
		reset($_GET);
		while(list($key, $val) = each($_GET)) {
			if($key!="name" && $key!="dirname") {
				$getparams.="-". $key ."_". $val;
			}
		}
		$filename.=$getparams .".html";
		if (is_file($filename) && !isset($_GET["output"])) {
			readfile($filename);
			statlog($this->presence, $docuid);
			exit();
		} else {
			$doccache=mysql_query("SELECT cache FROM ". $GLOBALS["db_pref"] ."content_documents WHERE id='". $_SESSION["act_doc"] ."' and deleted='0' and checkin_by>0");
			if (mysql_num_rows($doccache)==1) {
				$row_doccache=mysql_fetch_object($doccache);
				if ($row_doccache->cache==1) {
					$this->cache=1;
					$this->cachefilename=$filename;
				}
			}
		}
	}

	/**
	* @return void
	* @desc Adds standard nodes
	*/
	public function add_standards() {
		if ($this->editmode==1) {
			$this->add_node("editmode", "1");
		} else {
			$this->add_node("editmode", "0");
		}
		if (!empty($_SESSION["userid"])) {
			$this->add_node("adminmode", "1");
		}
		$this->add_node("sitename", getsetting("sitename"));
		$this->add_node("production_url", getsetting("production_url"));
		$this->add_node("copyright", getsetting("copyright"), null, null, 1);
		if(!defined("PRODUCTION_URL")) {
			define("PRODUCTION_URL", getsetting("production_url"));
		}
		$this->add_node("admin_url", getsetting("admin_url"));
		$isdir=0;
		if(substr($_SERVER["REQUEST_URI"],(strlen($_SERVER["REQUEST_URI"]) - 1),1)=="/") {
			$isdir=1;
		}
		$this->add_node("request_uri", $_SERVER["REQUEST_URI"],null,array("dir"=>$isdir));
		$zusatz="";
		if (isset($_GET["name"])) {
			$zusatz.="&name=". $_GET["name"];
		}
		if (isset($_GET["dirname"])) {
			$zusatz.="&dirname=". $_GET["dirname"];
		}
		$this->add_node("filename", $_SERVER["PHP_SELF"] ."?". $zusatz);
		$this->add_node("realfilename", $_SERVER["PHP_SELF"]);
		$this->add_node("filenamezusatz", $zusatz);
		if(!defined("FILENAME")) {
			if($this->editmode==1) {
				define("FILENAME", $_SERVER["PHP_SELF"] ."?". $zusatz);
			} else {
				define("FILENAME", $_SERVER["REQUEST_URI"]);
			}
		}
		if(!defined("FILENAMEZUSATZ")) {
			define("FILENAMEZUSATZ", $zusatz);
		}
		if(!defined("REALFILENAME")) {
			if($this->editmode==1) {
				define("REALFILENAME", $_SERVER["PHP_SELF"] ."?". $zusatz);
			} elseif(isset($_SERVER["REDIRECT_URL"]) && $_SERVER["REDIRECT_URL"]!=$_SERVER["PHP_SELF"]) {
				$requesturi=explode("/", $_SERVER["REDIRECT_URL"]);
				define("REALFILENAME", "/". $requesturi[1]);
			} else {
				$requesturi=explode("/", $_SERVER["REQUEST_URI"]);
				define("REALFILENAME", "/". $requesturi[1]);
			}
		}
		$this->add_node("realurl", REALFILENAME);
		if(isset($_SESSION["login_webuser"])) {
			$this->add_node("login_webuser", trim($_SESSION["login_webuser"]));
		}
	}

	/**
	* @return void
	* @desc Adds standard nodes
	*/
	public function add_document_infos($contents) {
		$this->add_node("webtitle", htmlentities(utf8_decode($contents->webtitle)), null, null, 1);
		$this->add_node("checkin_by", htmlentities(utf8_decode($contents->checkinby)), null, null, 1);
		$this->add_node("checkin_date", htmlentities(utf8_decode($contents->checkindate)), null, null, 1);
		$this->add_node("description", htmlentities(utf8_decode($contents->description)), null, null, 1);
		$this->add_node("keywords", htmlentities(utf8_decode($contents->keywords)), null, null, 1);
	}

	public function array2xml($array, $parseurl=1) {
		// echo $parseurl;
		$this->add_node("contents");
		if (is_array($array)) {
			for ($i_rep=0; $i_rep<count($array); $i_rep++) {
				$this->add_node("repetition", "", "/contents", array("id"=>$array[$i_rep][0], "name"=>$array[$i_rep][1], "sort"=>$array[$i_rep][2], "template"=>$array[$i_rep][4], "module"=>$array[$i_rep][6]));
				for ($j_rep=0; $j_rep<count($array[$i_rep][3]); $j_rep++) {
					$array[$i_rep][3][$j_rep][2]=htmlentities($array[$i_rep][3][$j_rep][2]);
					$array[$i_rep][3][$j_rep][2]=str_replace("&lt;","<", $array[$i_rep][3][$j_rep][2]);
					$array[$i_rep][3][$j_rep][2]=str_replace("&gt;",">", $array[$i_rep][3][$j_rep][2]);
					$array[$i_rep][3][$j_rep][2]=str_replace("&quot;","\"", $array[$i_rep][3][$j_rep][2]);
					$array[$i_rep][3][$j_rep][2]=str_replace("&amp;nbsp;","", $array[$i_rep][3][$j_rep][2]);
					$array[$i_rep][3][$j_rep][2]=str_replace("&nbsp;","", $array[$i_rep][3][$j_rep][2]);
					$array[$i_rep][3][$j_rep][2]=str_replace("&amp;#","&#", $array[$i_rep][3][$j_rep][2]);
					$edit=0;
					if ($this->editmode==1 && (!empty($_GET["editblock"]) && $_GET["editblock"]==$array[$i_rep][3][$j_rep][1] && !empty($_GET["editrepetition"]) && $_GET["editrepetition"]==$array[$i_rep][0])) {
						$edit=1;
					}
					$this->add_node("block", $array[$i_rep][3][$j_rep][2], "/contents/repetition[@id='". $array[$i_rep][0] ."']", array("id"=>$array[$i_rep][3][$j_rep][0], "name"=>$array[$i_rep][3][$j_rep][1], "edit"=>$edit), 1);
				}
				for ($j_rep=0; $j_rep<count($array[$i_rep][5]); $j_rep++) {
					$array[$i_rep][5][$j_rep][2]=htmlentities($array[$i_rep][5][$j_rep][2]);
					$array[$i_rep][5][$j_rep][2]=str_replace("&lt;","<", $array[$i_rep][5][$j_rep][2]);
					$array[$i_rep][5][$j_rep][2]=str_replace("&gt;",">", $array[$i_rep][5][$j_rep][2]);
					$array[$i_rep][5][$j_rep][2]=str_replace("&quot;","\"", $array[$i_rep][5][$j_rep][2]);
					$array[$i_rep][5][$j_rep][2]=str_replace("&amp;nbsp;","", $array[$i_rep][5][$j_rep][2]);
					$array[$i_rep][5][$j_rep][2]=str_replace("&nbsp;","", $array[$i_rep][5][$j_rep][2]);
					$array[$i_rep][5][$j_rep][2]=str_replace("&amp;#","&#", $array[$i_rep][5][$j_rep][2]);
					$edit=0;
					$link="";
					if(isset($array[$i_rep][5][$j_rep][3])) {
						$link=$array[$i_rep][5][$j_rep][3];
					}
					$this->add_node("image", $array[$i_rep][5][$j_rep][2], "/contents/repetition[@id='". $array[$i_rep][0] ."']", array("id"=>$array[$i_rep][5][$j_rep][0], "name"=>$array[$i_rep][5][$j_rep][1], "edit"=>$edit, "link"=>$link), 1);
				}
				if($array[$i_rep][4]=="" && $array[$i_rep][6]!="") {
					ob_start();
					// global $act_repetition;
					// $GLOBALS["act_repetition"]=$array[$i_rep][7];
					// $GLOBALS["act_mod_dir"]="../modules/". $array[$i_rep][6];
					include_once("../modules/". $array[$i_rep][6] ."/output.php");
					eval("output_". $array[$i_rep][6] ."(\"". $array[$i_rep][7] ."\", \"". "../modules/". $array[$i_rep][6] ."\", \"". $array[$i_rep][0] ."\");");
					$modoutput=ob_get_contents();
					ob_end_clean();
					$modoutput=$this->replace_url($modoutput);
					$this->add_node("rendered", $this->replace_url($modoutput), "/contents/repetition[@id='". $array[$i_rep][0] ."']", null, 1);
				} else {
					$this->add_node("rendered", $this->create_textblock_doc($array[$i_rep][0], $array[$i_rep][4], $parseurl), "/contents/repetition[@id='". $array[$i_rep][0] ."']", null, 1);
				}
			}
		}
	}

	public function replace_imgurl($str) {
		$links=explode("src=\"image://", $str);
		for ($i=1; $i<count($links); $i++) {
			$links2=explode("\"", $links[$i]);
			$link=$links2[0];
			// print_r($link);
			$linkentry=mysql_query("SELECT * FROM ". $GLOBALS["db_pref"] ."media WHERE id='". $link ."'");
			if (mysql_num_rows($linkentry)==1) {
				$row_link=mysql_fetch_object($linkentry);
				$mediapath=getsetting("production_url");
				$str=str_replace("src=\"image://". $link ."\"", "src=\"". $mediapath ."/media/". $row_link->filename ."\"", $str);
			}
		}
		return $this->replace_css_imgurl($str);
	}
	
	public function replace_css_imgurl($str) {
		$links=explode("('image://", $str);
		for ($i=1; $i<count($links); $i++) {
			$links2=explode("'", $links[$i]);
			$link=$links2[0];
			// print_r($link);
			$linkentry=mysql_query("SELECT * FROM ". $GLOBALS["db_pref"] ."media WHERE id='". $link ."'");
			if (mysql_num_rows($linkentry)==1) {
				$row_link=mysql_fetch_object($linkentry);
				$mediapath=getsetting("production_url");
				$str=str_replace("('image://". $link ."'", "('". $mediapath ."/media/". $row_link->filename ."'", $str);
			}
		}
		return $str;
	}

	public function replace_docurl($str) {
		$links=explode("href=\"doclink://", $str);
		for ($i=1; $i<count($links); $i++) {
			$links2=explode("\"", $links[$i]);
			$link=$links2[0];
			// echo "SELECT * FROM ". $GLOBALS["db_pref"] ."content_documents WHERE id='". $link ."' AND deleted='0'" ."<br>";
			$linkentry=mysql_query("SELECT * FROM ". $GLOBALS["db_pref"] ."content_documents WHERE id2='". $link ."' and checkin_by>0 AND deleted='0'");
			if (mysql_num_rows($linkentry)==1) {
				$row_link=mysql_fetch_object($linkentry);
				$url="";
				if(isset($_SESSION["userid"])) {
					$url="/admin_content_edit.php?name=". $row_link->id2;
				} else {
					$url="/". $row_link->shortname .".html";
				}
				$str=str_replace("<a href=\"doclink://". $link ."\">", "<a href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\">", $str);

			}
		}
		return $str;
	}
	
	public function replace_url($str) {
		$links=explode("href=\"link://", $str);
		for ($i=1; $i<count($links); $i++) {
			$links2=explode("\"", $links[$i]);
			$link=$links2[0];
			$linkentry=mysql_query("SELECT * FROM ". $GLOBALS["db_pref"] ."content_links WHERE id='". $link ."'");
			if (mysql_num_rows($linkentry)==1) {
				$row_link=mysql_fetch_object($linkentry);
				if ($row_link->type==1) {
					$content_doc=mysql_query("SELECT id2, shortname FROM ". $GLOBALS["db_pref"] ."content_documents WHERE id='". $row_link->url ."' and deleted='0' and checkin_by!='0'");
					if (mysql_num_rows($content_doc)==1) {
						$row_doc=mysql_fetch_object($content_doc);
						$class="";
						if ($row_link->class!="") {
							$class=" class=\"". $row_link->class ."\"";
						}
						$url="";
						if(isset($_SESSION["userid"])) {
							$url="/admin_content_edit.php?name=". $row_doc->id2;
						} else {
							$url="/". $row_doc->shortname .".html";
						}
						$zusatztarget="";
						if($row_link->target=="_blank") {
							$zusatztarget="onclick=\"window.open(this.href); return false;\"";
						}
						//$str=str_replace("href=\"link://". $link ."\">", "href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" target=\"". $row_link->target ."\"". $class .">", $str);
						$str=str_replace("href=\"link://". $link ."\">", "href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" ". $zusatztarget ."". $class .">", $str);
					} else {
						$str=preg_replace("/<a href=\"link:\/\/". $link ."\">(.*)?<\/a>/i", "$1", $str);
						// disabled by mthie. If needed please re-uncomment
						// $str=str_replace("<a href=\"link://". $link ."\">", "<a href=\"#\">", $str);
					}
				} elseif ($row_link->type==2) {
					$class="";
					if ($row_link->class!="") {
						$class="class=\"". $row_link->class ."\"";
					}
					$zusatztarget="";
					if($row_link->target=="_blank") {
						$zusatztarget="onclick=\"window.open(this.href); return false;\"";
					}
					$str=str_replace("href=\"link://". $link ."\">", "href=\"". $row_link->url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" ". $zusatztarget ."". $class .">", $str);
					// $str=str_replace("href=\"link://". $link ."\">", "href=\"". $row_link->url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" target=\"". $row_link->target ."\"". $class .">", $str);
				} elseif ($row_link->type==3) {
					$content_doc=mysql_query("SELECT id, shortname FROM ". $GLOBALS["db_pref"] ."navigation WHERE id='". $row_link->url ."' and deleted='0'");
					if (mysql_num_rows($content_doc)==1) {
						$row_doc=mysql_fetch_object($content_doc);
						$class="";
						if ($row_link->class!="") {
							$class="class=\"". $row_link->class ."\"";
						}

						$url="";
						if(isset($_SESSION["userid"])) {
							$url="/admin_content_edit.php?dirname=". $row_doc->id;
						} else {
							$url="/". $row_doc->shortname ."/";
						}
						$zusatztarget="";
						if($row_link->target=="_blank") {
							$zusatztarget="onclick=\"window.open(this.href); return false;\"";
						}
						// $str=str_replace("href=\"link://". $link ."\">", "href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" target=\"". $row_link->target ."\"". $class .">", $str);
						$str=str_replace("href=\"link://". $link ."\">", "href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" ". $zusatztarget ."". $class .">", $str);
					} else {
						$str=preg_replace("/<a href=\"link:\/\/". $link ."\">(.*)?<\/a>/i", "$1", $str);
						// disabled by mthie. If needed please re-uncomment
						// $str=str_replace("<a href=\"link://". $link ."\">", "<a href=\"#\">", $str);
					}
				} elseif ($row_link->type==4) {
					$media_doc=mysql_query("SELECT filename FROM ". $GLOBALS["db_pref"] ."media WHERE id='". $row_link->url ."'");
					if (mysql_num_rows($media_doc)==1) {
						$row_media=mysql_fetch_object($media_doc);
						$class="";
						if ($row_link->class!="") {
							$class="class=\"". $row_link->class ."\"";
						}
						
						$mediapath=getsetting("production_url");

						$url="";
						$url=$mediapath ."/media/". $row_media->filename;

						$zusatztarget="";
						if($row_link->target=="_blank") {
							$zusatztarget="onclick=\"window.open(this.href); return false;\"";
						}
						
						// $str=str_replace("href=\"link://". $link ."\">", "href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" target=\"". $row_link->target ."\"". $class .">", $str);
						$str=str_replace("href=\"link://". $link ."\">", "href=\"". $url ."\" tabindex=\"". $i ."\" accesskey=\"". $i ."\" ". $zusatztarget ."". $class .">", $str);
					} else {
						$str=preg_replace("/<a href=\"link:\/\/". $link ."\">(.*)?<\/a>/i", "$1", $str);
						// disabled by mthie. If needed please re-uncomment
						// $str=str_replace("<a href=\"link://". $link ."\">", "<a href=\"#\">", $str);
					}
				}
			} else {
				$str=preg_replace("/<a href=\"link:\/\/". $link ."\">(.*)?<\/a>/i", "$1", $str);
			}
		}
		return $this->replace_imgurl($str);
	}

	public function getblocktemplates() {
		$dirname=realpath("./../". getsetting("templatedir")) ."/repetitions";
		$dir=opendir($dirname);
		$this->add_node("blocktemplates");
		while (false!==($file=readdir($dir))) {
			if ($file!="." && $file!=".." && is_file($dirname ."/". $file) && $file!="CVS" && !stristr(".svn", $file) && substr($file,0,1)!="_") {
				$this->add_node("block", substr($file,0,((strlen($file)) - 4)), "/blocktemplates");
			}
		}
		closedir($dir);
	}
	
	public function getmodules($pres) {
		$dirname=realpath("./../modules");
		$dir=opendir($dirname);
		$this->add_node("modules");
		while (false!==($file=readdir($dir))) {
			if ($file!="." && $file!=".." && is_dir($dirname ."/". $file) && file_exists($dirname ."/". $file ."/output.php") && $file!="CVS" && !stristr(".svn", $file) && substr($file,0,1)!="_") {
				$checkright=mysql_query("SELECT * FROM ". $GLOBALS["db_pref"] ."presences_modules WHERE presence='". $pres ."' and name='". $file ."'");
				if (mysql_num_rows($checkright)>0) {
					$this->add_node("modul", $file, "/modules");
				}
			}
		}
		closedir($dir);
	}

	public function create_textblock_doc($textblock, $template, $parsed_links=1) {
		// echo $template;
		$newdoc = new DOMDocument("1.0", "UTF-8");
		$root = $newdoc->createElement("document");
		$newdoc->appendChild($root);
		$editmode = $newdoc->createElement("editmode", $this->read_node("/editmode"));
		$root->appendChild($editmode);
		$editmode = $newdoc->createElement("production_url", $this->read_node("/production_url"));
		$root->appendChild($editmode);
		$adminurl = $newdoc->createElement("admin_url", $this->read_node("/admin_url"));
		$root->appendChild($adminurl);
		$presence = $newdoc->createElement("presence", $this->read_node("/presence"));
		$root->appendChild($presence);
		$filename=$newdoc->createElement("filename", "");
		$newcdata=$newdoc->createCDATASection($this->read_node("/filename"));
		$filename->appendChild($newcdata);
		$root->appendChild($filename);

		$filename=$newdoc->createElement("filenamezusatz", "");
		$newcdata=$newdoc->createCDATASection($this->read_node("/filenamezusatz"));
		$filename->appendChild($newcdata);
		$root->appendChild($filename);
		// $newdoc=new XML();
		$node=$this->get_xpath_node("/contents/repetition[@id='". $textblock ."']");
		if ($node->length>0) {
			for($i=0; $i<$node->length; $i++) {
				$oldNode=$node->item($i);
				$root->appendChild($newdoc->importNode($oldNode->cloneNode(true), true));
				// echo $newdoc->saveXML();
				$output=$this->output("repetitions/". $template, 1, $newdoc, 1);
				if ($parsed_links==1) {
					return $this->replace_docurl($this->replace_url($output));
				} else {
					return $output;
				}
				//	exit();
			}
		}
	}

	public function navarray2xml($array, $startnode="") {
		if ($startnode=="") {
			$this->add_node("navigation");
			$startnode.="/navigation";
		}
		for($i=0; $i<count($array);$i++) {
			$this->add_node("navigation", "", $startnode, array("id"=>$array[$i]["id"], "active"=>$array[$i]["active"]));
			$newstartnode=$startnode . "/navigation[@id='". $array[$i]["id"] ."']";
			$this->add_node("name", htmlentities($array[$i]["name"]), $newstartnode, null, 1);
			$this->add_node("shortname", htmlentities($array[$i]["shortname"]), $newstartnode, null, 0);
			$this->add_node("linktarget", $array[$i]["linktarget"], $newstartnode);
			$this->add_node("graphic", $array[$i]["graphic"], $newstartnode, null, 1);
			$this->add_node("overgraphic", $array[$i]["overgraphic"], $newstartnode, null, 1);
			$this->add_node("active", $array[$i]["active"], $newstartnode, null);
			$this->add_node("children", "", $newstartnode);
			$this->navarray2xml($array[$i]["subs"], $newstartnode ."/children");
		}
	}
	
	public function replace_modules($output) {
		$modules=explode("<module name=\"", $output);
		for($i=1; $i<count($modules); $i++) {
			$mod=explode("\"/>", $modules[$i]);
			$ext_module=$mod[0];
			ob_start();
			include_once("../modules/". $ext_module ."/output.php");
			eval("output_". $ext_module ."(\"0\", \"". "../modules/". $ext_module ."\");");
			$modoutput=ob_get_contents();
			ob_end_clean();
			$output=str_replace("<module name=\"". $ext_module ."\"/>", $modoutput, $output);
		}
		return $output;
	}

	function output($template, $return=0, $xmltree=null, $disable_xmloutput=0, $docuid='') {
		if (((isset($_GET["show_xml"]) && $_GET["show_xml"]=="1" && $return==0) || stristr($_SERVER["REQUEST_URI"], "show_xml=1")) && $disable_xmloutput==0 && getsetting("debug_mode")=="1" && $disable_xmloutput==0) {
			$this->dump_xml();
		} else {
			$xsl=new XSLTProcessor();
			$template_dir="../". getsetting("templatedir") ."/";
			// echo $template_dir . $template;
			header("Content-Type:text/html");
			if(empty($template)) {
				$template="empty.xsl";
			}
			if (is_file($template_dir . $template)) {
				$xsl->importStylesheet(DOMDocument::load($template_dir . $template));
				if ($xmltree!=null) {
					$output=$xsl->transformToXML($xmltree);
				} else {
					$output=$xsl->transformToXML($this->doc);
				}
				
				if($this->replaceglobalurls==1) {
					$output=$this->replace_docurl($this->replace_url($output));
				}
				if ($this->cache==1) {
					$fp=fopen($this->cachefilename, "w");
					fwrite($fp, $output);
					fclose($fp);
				}
				if(isset($_GET["output"]) && $return==0) {
					$cache_dir=realpath($this->cachefilename);
					$dirstring=explode("/", $cache_dir);
					$new_cache_dir="";
					for($d=0; $d < (count($dirstring) - 1); $d++) {
						if($d>0) {
							$new_cache_dir.="/";
						}
						$new_cache_dir.=$dirstring[$d];
					}
					$cache_dir=$new_cache_dir;
					if(!is_dir($cache_dir ."/pdfcache")) {
						mkdir($cache_dir ."/pdfcache");
					}

					if($_GET["output"]=="pdf") {
						if(isset($GLOBALS["fop"]) && $GLOBALS["fop"]["active"]==1) {
							/*
							$xsl->importStylesheet(DOMDocument::load($template_dir ."/fop/". $template));
							if ($xmltree!=null) {
								$pdfoutput=$xsl->transformToXML($xmltree);
							} else {
								$pdfoutput=$xsl->transformToXML($this->doc);
							}*/
							$xmltree=$this->dump_xml(1);
							$fp=fopen($this->cachefilename ."_pdf", "w");
							fwrite($fp, $xmltree);
							fclose($fp);
							$pdf_cachefile=str_replace($cache_dir ."/", "",$this->cachefilename);
							$fopoutput=exec($GLOBALS["fop"]["command"] ." ". $GLOBALS["fop"]["params"] ." -xsl ". $template_dir ."/fop/". $template ." -xml ". $this->cachefilename ."_pdf -pdf ". $cache_dir ."/pdfcache/". $pdf_cachefile .".pdf");
							if(is_file($cache_dir ."/pdfcache/". $pdf_cachefile .".pdf")) {
								header("Content-Type: application/pdf");
								header("Content-Disposition: inline; filename=output.pdf");
								header("HTTP/1.1 200 OK");
								readfile($cache_dir ."/pdfcache/". $pdf_cachefile .".pdf");
								exit();
							} else {
								die("Das Erzeugen der PDF ist fehlgeschlagen.");
							}
						} elseif(isset($GLOBALS["htmldoc"]) && $GLOBALS["htmldoc"]["active"]==1) {
							$xsl->importStylesheet(DOMDocument::load($template_dir ."/pdf/". $template));
							if ($xmltree!=null) {
								$pdfoutput=$xsl->transformToXML($xmltree);
							} else {
								$pdfoutput=$xsl->transformToXML($this->doc);
							}
							
							$fp=fopen($this->cachefilename ."_pdf", "w");
							fwrite($fp, $pdfoutput);
							fclose($fp);
							// echo $GLOBALS["htmldoc"]["command"] ." ". $GLOBALS["htmldoc"]["params"] ." ". $this->cachefilename ."_pdf";
							header("Content-Type: application/pdf");
							header("Content-Disposition: inline; filename=output.pdf");
							header("HTTP/1.1 200 OK");
							flush();
							$pdf_cachefile=str_replace($cache_dir ."/", "",$this->cachefilename);
							system($GLOBALS["htmldoc"]["command"] ." ". $GLOBALS["htmldoc"]["params"] ." ". $this->cachefilename ."_pdf >> ". $cache_dir ."/pdfcache/". $pdf_cachefile .".pdf");
							readfile($cache_dir ."/pdfcache/". $pdf_cachefile .".pdf");
							exit();
						}
					}
				}
				$output=str_replace("\r", "", $output);
				// $output=str_replace("\n", "", $output);
				$output=str_replace("\t", "", $output);
				$output=str_replace("> <", "><", $output);
				$output=$this->replace_modules($output);
				$newoutput="";
				if($return==0) {
					$xmltrim=explode("<"."?xml", $output);
					if(isset($xmltrim[1])) {
						$newoutput.="<"."?xml".$xmltrim[1];
					}
					for($i=2; $i<count($xmltrim); $i++) {
						$xmltrimrest=explode("?".">", $xmltrim[$i]);
						if (isset($xmltrim[$i]) && isset($xmltrimrest[1])) {
							$newoutput.=$xmltrimrest[1];
						}
					}
					$output=$newoutput;
				}
				
				if($return==0) {
					echo $output;
					statlog($this->presence, $docuid);
				} else {
					return $output;
				}
			} else {
				return "Bitte w&auml;hlen Sie ein Template aus!";
			}
		}
	}

	function dump_xml($return=0) {
		header("Content-Type:text/xml");
		if($return==0) {
			echo $this->doc->saveXML();
		} else {
			return $this->doc->saveXML();
		}
	}
}
?>
